import { useEffect, useState } from 'react';
import { toastError } from '../toast-error';
import Button from '../ui/Button';
import toast from 'react-hot-toast';

type VcodeButtonProps = {
  phone: string;
  sendVcodeApi: (phone: string) => Promise<void>;
};

export default function VcodeButton({ phone, sendVcodeApi }: VcodeButtonProps) {
  const [leftSeconds, setLeftSeconds] = useState(0);

  const sendVcode = async () => {
    if (!phone) {
      toast.error('尚未填入手机号');
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      toast.error('手机号格式不正确');
      return;
    }

    setLeftSeconds(60);
    await sendVcodeApi(phone).catch((err) => {
      setLeftSeconds(0);
      toastError(err);
    });
  };

  useEffect(() => {
    if (leftSeconds === 0) return;
    const timer = setTimeout(() => {
      setLeftSeconds((leftSeconds) => (leftSeconds >= 1 ? leftSeconds - 1 : 0));
      clearTimeout(timer);
    }, 1000);
  }, [leftSeconds]);

  const disabled = leftSeconds > 0;

  return (
    <Button noRound className="rounded-r-md flex justify-center w-60" disabled={disabled} onClick={sendVcode}>
      {disabled ? `${leftSeconds}秒` : '获取验证码'}
    </Button>
  );
}
